package com.lzb.provide;

import android.content.ContentProvider;
import android.content.ContentValues;
import android.content.UriMatcher;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteQueryBuilder;
import android.net.Uri;
import android.support.annotation.Nullable;
import android.text.TextUtils;

/**
 *
 * 自定义 内容提供者
 * <h3>Description</h3>
 * TODO
 * <h3>Author</h3> Eric
 * <h3>Date</h3> 2017/10/20 09:56
 * <h3>Copyright</h3> Copyright (c)2017 Shenzhen TLKY  Co., Ltd. Inc. All rights reserved.
 */
public class MyContentProvide extends ContentProvider {

    public static final String SCHEME = "content"; // 源码里面规定这样写，所以这个地方改变不了
    public static final String PORT = "200";

    /** uri 规则*/
//    public static final Uri CONTENT_URI = Uri.parse(SCHEME + "://" + HOST + ":" + PORT + "/" + PATH);
    public static final String SHARE_LIST_TYPE = "vnd.android.cursor.dir/";
    public static final String SHARE_ITEM_TYPE = "vnd.android.cursor.item/";

    /**标识码*/
    public static final int CODE_ID_1 = 1;
    public static final int CODE_ID_2 = 2;
    public static final String HOST = "com.lzb.provide.myContentProvide";
    /**路径*/
    public static final String PATH = "students";
    /**初始化UriMatcher工具类*/
    private static UriMatcher uriMatcher = new UriMatcher(UriMatcher.NO_MATCH);
    static {
        // # 为通配符
        uriMatcher.addURI(HOST,PATH,CODE_ID_1);
        uriMatcher.addURI(HOST,PATH + "/#",CODE_ID_2);
    }

    public static final Uri CONTENT_URI = Uri.parse(SCHEME + "://" + HOST +  "/" + PATH);

    private SQLiteOpenHelperUtil sqLiteOpenHelperUtil;

    /**
     * 该方法在ContentProvider创建后会被调用，当其他应用程序第一次访问ContentProvide时，
     * 该ContentProvider会被创建出来，并立即回调该onCreate方法
     * @return
     */
    @Override
    public boolean onCreate() {
        sqLiteOpenHelperUtil = new SQLiteOpenHelperUtil(getContext());
        return sqLiteOpenHelperUtil != null;
    }

    /**
     * 根据Uri查询出select条件所匹配的全部记录，projection表示一个列名列表，表明只选择指定的数据列
     * @param uri
     * @param projection
     * @param selection
     * @param selectionArgs
     * @param sortOrder
     * @return
     */
    @Nullable
    @Override
    public Cursor query(Uri uri, String[] projection, String selection, String[] selectionArgs, String sortOrder) {
        // 首先是看Uri和我们自定义的是否匹配，，匹配则将数据属性插入到数据库中并同志更新
        SQLiteDatabase sqLiteDatabase = sqLiteOpenHelperUtil.getReadableDatabase();
        //SQLiteQueryBuilder是一个构造SQL查询语句的辅助类
        SQLiteQueryBuilder builder  = new SQLiteQueryBuilder();
        //根据前面注册的Uri返回对应的标识码，如果找不到返回-1
        int code = uriMatcher.match(uri);
        Cursor cursor = null;
        switch (code){
            case CODE_ID_1:
//                cursor =  sqLiteDatabase.query(SQLiteOpenHelperUtil.TABLE_NAME,
//                        new String[]{SQLiteOpenHelperUtil.ID,SQLiteOpenHelperUtil.MESSAGE},selection,selectionArgs,null,null,sortOrder);
                builder.setTables(SQLiteOpenHelperUtil.TABLE_NAME);
                break;
            case CODE_ID_2:
                //设置要查询的表名
                builder.setTables(SQLiteOpenHelperUtil.TABLE_NAME);
                //添加条件
                builder.appendWhere(SQLiteOpenHelperUtil.STUDENT_ID + "=" + uri.getPathSegments().get(1));
                break;
            default:
                throw  new IllegalArgumentException("Unknown Uir :" + uri);
        }
        //使用负责类开始查询数据库
        cursor = builder.query(sqLiteDatabase,projection,selection,selectionArgs,null,null,sortOrder);
//        if (cursor != null){
//            //通知所用注册该Uri的监听者，数据发生了变化
//            getContext().getContentResolver().notifyChange(uri,null);
//        }
        return cursor;
    }

    /**
     * 返回 当前Uri所代表的数据的MIME类型。如果该Uri对应数据可能包括多条记录，
     * 那么MIME类型字符串应该以 vnd.android.cursor.dir/开头；如果该Uri对应的数据只包含一条记录，
     * 那么返回MIME类型字符串应该以vnd.android.cursor.item/开头。
     * @param uri
     * @return
     */
    @Nullable
    @Override
    public String getType(Uri uri) {
        //根据前面注册的Uri返回对应的标识码，如果找不到返回-1
        int code = uriMatcher.match(uri);
        switch (code){
            case CODE_ID_1:
                //vnd.android.cursor.dir/
                return SHARE_LIST_TYPE;
            case CODE_ID_2:
                //vnd.android.cursor.item/
                return SHARE_ITEM_TYPE;
            default:
                throw  new IllegalArgumentException("Unknown Uir :" + uri);
        }
    }

    /**
     * 根据该Uri插入values对应的数据
     * @param uri
     * @param values
     * @return
     */
    @Nullable
    @Override
    public Uri insert(Uri uri, ContentValues values) {
        // 首先是看Uri和我们自定义的是否匹配，，匹配则将数据属性插入到数据库中并同志更新
        SQLiteDatabase sqLiteDatabase = sqLiteOpenHelperUtil.getWritableDatabase();
        if (uriMatcher.match(uri) != CODE_ID_1) {
            throw new IllegalArgumentException("Unknown/Invalid URI : " + uri);
        }
        //行 id
        long rowID = sqLiteDatabase.insert(SQLiteOpenHelperUtil.TABLE_NAME,null,values);
        if (rowID != -1){ //添加数据成功
            //通知所用注册该Uri的监听者，数据发生了变化
            getContext().getContentResolver().notifyChange(uri,null);
        }
        return Uri.parse(SCHEME + "://" + HOST +  "/" + PATH +  "/" + values.getAsInteger(SQLiteOpenHelperUtil.STUDENT_ID));
    }

    @Override
    public int delete(Uri uri, String selection, String[] selectionArgs) {
        // 首先是看Uri和我们自定义的是否匹配，，匹配则将数据属性插入到数据库中并同志更新
        SQLiteDatabase sqLiteDatabase = sqLiteOpenHelperUtil.getWritableDatabase();
        //根据前面注册的Uri返回对应的标识码，如果找不到返回-1
        int code = uriMatcher.match(uri);
        long studentId = 0;
        String where ;
        switch (code){
            case CODE_ID_1:
                if (!TextUtils.isEmpty(selection)){
                    where = "(" + selection + ")";
                }else {
                    where = "";
                }
                break;
            case CODE_ID_2:
                if (!TextUtils.isEmpty(selection)){
                    where = "(" + selection + ") AND ";
                }else {
                    where = "";
                }
                String segment = uri.getPathSegments().get(1);
                studentId  = Long.valueOf(segment);
                where += "(" + SQLiteOpenHelperUtil.STUDENT_ID + "=" + studentId + ")";
                break;
            default:
                throw  new IllegalArgumentException("Unknown Uir :" + uri);
        }
        //受影响行数
        int count = sqLiteDatabase.delete(SQLiteOpenHelperUtil.TABLE_NAME, where, selectionArgs);
        getContext().getContentResolver().notifyChange(uri,null);
        return count;
    }

    @Override
    public int update(Uri uri, ContentValues values, String selection, String[] selectionArgs) {
        // 首先是看Uri和我们自定义的是否匹配，，匹配则将数据属性插入到数据库中并同志更新
        SQLiteDatabase sqLiteDatabase = sqLiteOpenHelperUtil.getWritableDatabase();
        //根据前面注册的Uri返回对应的标识码，如果找不到返回-1
        int code = uriMatcher.match(uri);
        long studentId = 0;
        String where ;
        switch (code){
            case CODE_ID_1:
                if (!TextUtils.isEmpty(selection)){
                    where = "(" + selection + ")";
                }else {
                    where = "";
                }
                break;
            case CODE_ID_2:
                if (!TextUtils.isEmpty(selection)){
                    where = "(" + selection + ") AND ";
                }else {
                    where = "";
                }
                String segment = uri.getPathSegments().get(1);
                studentId  = Long.valueOf(segment);
                where += "(" + SQLiteOpenHelperUtil.STUDENT_ID + "=" + studentId + ")";
                break;
            default:
                throw  new IllegalArgumentException("Unknown Uir :" + uri);
        }
        //受影响行数
        int count = 0;
        if (values.size() > 0 ){
            count = sqLiteDatabase.update(SQLiteOpenHelperUtil.TABLE_NAME,values,where,selectionArgs);
            getContext().getContentResolver().notifyChange(uri,null);
        }
        return count;
    }
}
